package com.joysuch.wwyt.edu.task;

import com.google.common.collect.Lists;
import com.joysuch.wwyt.edu.entity.EduTrainningPlan;
import com.joysuch.wwyt.edu.enums.TrainingPlanStates;
import com.joysuch.wwyt.edu.repository.EduTrainningPlanDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 培训计划任务
 * @author Leong
 * @date 2022/9/20 18:46
 */
@Slf4j
@Component
public class TrainingPlanTask {

    @Resource
    private EduTrainningPlanDao eduTrainningPlanDao;

    @Scheduled(initialDelay = 10000, fixedDelay = 10 * 1000)
    public void checkTrainingPlan() {
        List<EduTrainningPlan> plans = eduTrainningPlanDao.findAll();
        List<EduTrainningPlan> planList = Lists.newArrayList();
        Date currDate = new Date();
        for (EduTrainningPlan plan : plans){
            Integer state = plan.getState();
            if (plan.getImplementTime() != null){
                if (currDate.before(plan.getImplementTime())){
                    plan.setState(TrainingPlanStates.NOT_STARTED.getId());
                }
                if (plan.getFinishTime() != null && currDate.after(plan.getImplementTime()) && currDate.before(plan.getFinishTime())){
                    plan.setState(TrainingPlanStates.INPROGRESSING.getId());
                }
                if (plan.getFinishTime() == null && currDate.after(plan.getImplementTime())){
                    plan.setState(TrainingPlanStates.INPROGRESSING.getId());
                }
            }
            if (plan.getFinishTime() != null){
                if (plan.getFinishTime().before(currDate)){
                    plan.setState(TrainingPlanStates.OUT_OF_DATE.getId());
                }
                if (plan.getImplementTime() == null && plan.getFinishTime().after(currDate)){
                    plan.setState(TrainingPlanStates.NOT_STARTED.getId());
                }
            }
            if (plan.getState() == null){
                plan.setState(TrainingPlanStates.OUT_OF_DATE.getId());
            }
            if (!plan.getState().equals(state)){
                planList.add(plan);
            }
        }
        if (CollectionUtils.isNotEmpty(planList)){
            eduTrainningPlanDao.saveAll(planList);
        }
    }
}
